package agriculture.mq;

import agriculture.bean.Order;
import agriculture.config.RabbitMQConfig;
import agriculture.mapper.OrderMapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.RequiredArgsConstructor;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

@Component
@RequiredArgsConstructor
public class OrderTimeoutListener {
    private final OrderMapper orderMapper;

    @RabbitListener(queues = RabbitMQConfig.DEAD_QUEUE_NAME)
    public void handleOrderTimeout(String orderNumber) {
        System.out.println("延迟队列取消服务-------------");
        try {
            System.out.println("接收到超时订单编号：" + orderNumber);
            QueryWrapper<Order> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("order_number", orderNumber);
            Order order = orderMapper.selectOne(queryWrapper);

            if (order != null && "0".equals(order.getStatus())) {
                order.setStatus("2"); // 订单取消
                orderMapper.updateById(order);
                System.out.println("订单超时未支付，已自动取消：" + orderNumber);
            }
        } catch (Exception e) {
            System.err.println("处理超时订单失败：" + orderNumber);
            e.printStackTrace();
        }
    }
}
